package sortingRMI_client;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Observable;
import java.util.concurrent.TimeUnit;

import sortingRMI_server.ISortFactory;

@SuppressWarnings("unchecked")
public class SorterThread extends Observable implements Runnable {
	
	private Comparable[] unsortedArray;
	private Comparable[] sortedArray;
	private String name;
	private Thread thread;
	private SorterThread st;
	
	public SorterThread(Comparable[] unsortedArray, String threadName) {
	
		this.unsortedArray = unsortedArray;
		this.name = threadName;
	}
	
	@Override
	public void run() {
		int i;
		try {
			for (i=0; i<unsortedArray.length; i++) {
				((MuziekCD) unsortedArray[i]).setThreadName(getThreadName());
			}
 			sortedArray = sort(unsortedArray);
		} catch(Exception e) {}
		tellThreadJoiner();
	}

	public void start() {
			thread = new Thread(this,getThreadName());
			thread.start();
	}
	
	public void tellThreadJoiner() {
		setChanged();
		notifyObservers(st);
	}
	
	private Comparable[] sort(Comparable[] unsortedArray) {
		long startTime = 0;
		long endTime = 0;
		long elapsedTime = 0;
		
		try {
			Registry registry = LocateRegistry.getRegistry("127.0.0.1",10001);
			ISortFactory sf = (ISortFactory) registry.lookup("sf");
		
			startTime = System.nanoTime();
			sortedArray = sf.createSorter().sort(unsortedArray);
			endTime = System.nanoTime();
			elapsedTime = endTime-startTime;
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		System.out.println("Sorting on thread " + getThreadName() + " took " + TimeUnit.NANOSECONDS.toMillis(elapsedTime) + " milliseconds");
		return sortedArray;
	}
	
	public Comparable[] getSortedArray() {
		return sortedArray;
	}
	
	public String getThreadName() {
		return name;
	}
	
//	public int getNextThreadNumber() {
//		
//	}
	
}
